<template>
  <basic-container class="Synchronize">
    <div class="filter_container">
      <el-form :inline="true" :model="Synchronizeform" class="demo-form-inline">
        <div class="Synchronizeflex">
          <el-form-item label="后台单号:">
            <el-input placeholder="请输入后台单号" v-model.trim="Synchronizeform.xmbzNo" size="small" clearable
              @keyup.enter.native='handleFilter(Launchdate)'>
            </el-input>
          </el-form-item>
          <el-form-item label="平台单号:">
            <el-input placeholder="请输入平台单号" v-model.trim="Synchronizeform.platformNo" size="small" clearable
              @keyup.enter.native='handleFilter(Launchdate)'>
            </el-input>
          </el-form-item>
          <el-form-item label="同步失败日期:">
            <el-date-picker v-model="Launchdate" type="daterange" range-separator="至" start-placeholder="开始日期"
              :clearable='false' end-placeholder="结束日期" size="small">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="失败类型:">
            <el-select v-model="Synchronizeform.failType" clearable placeholder="请选择失败类型" size="small" @visible-change='handlefailureType'
              ref='failTypeRef' @keydown.native="selectBlur($event)">
              <el-option v-for="item in failureTypelist" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="配送费:">
            <el-select v-model="Synchronizeform.deliveryfee" clearable placeholder="请选择" size="small" style='width: 120px;'>
              <el-option v-for="item in deliveryfeelist" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey">
              </el-option>
            </el-select>
          </el-form-item> -->
          <!--  </div>
        <div class="Synchronizeflex2"> -->
          <el-form-item>
            <el-button type="primary" plain size="small" icon="el-icon-search" @click="handleFilter(Launchdate)">查询</el-button>
            <el-button type="info" plain size="small" icon="el-icon-upload" @click="handleSynchronize(Synchronizeform,Launchdate)">同步到金蝶</el-button>
            <!--   <el-button type="success" plain size="small" icon="el-icon-download" @click="handleExport(Synchronizeform,Launchdate)">导出</el-button> -->
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="Synchronize">
      <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" :default-sort="{prop: 'delivey', order: 'descending'}"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="44">
        </el-table-column>
        <el-table-column label="后台单号" prop='xmbzNo' show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="平台单号" prop='platformNo' show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="金蝶单号" prop='kingdeeNo' show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="金蝶单号" prop='kingdeeNo' show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="updateTime" sortable label="同步失败时间">
        </el-table-column>
        <el-table-column sortable label="配送时间" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.deliveryStartTime }}~{{scope.row.deliveryEndTime}}</template>
          <!--  -->
        </el-table-column>
        <el-table-column prop="failTypeName" label="失败类型" show-overflow-tooltip>

        </el-table-column>
        <el-table-column prop="failReason" label="失败原因" show-overflow-tooltip>
        </el-table-column>
      </el-table>
    </div>
    <div style="display: flex;align-items: center;">
      <div style="color: #606266;" v-show="total>0">同步失败总数：{{total}}条</div>
      <pagination v-show="total>0" :total="total" :page.sync="Synchronizeform.page" :limit.sync="Synchronizeform.size"
        layout="sizes,prev, pager, next" @pagination="getList" />
    </div>
  </basic-container>
</template>

<script>
  import Pagination from "@/components/Pagination"; // 分页
  import {
    getKingdeeSynchronizationFailPage,
    synchronizationKingdeeFailOrder,
    kingdeefailtype
  } from "@/api/workorder.js"
  export default {
    components: {
      Pagination
    },
    data() {
      return {
        total: 3,
        Synchronizeform: {
          xmbzNo: '',
          platformNo: '',
          type: '',
          deliveryfee: '',
          startTime: this.dayjs(
              new Date()
            )
            .format("YYYY-MM-DD")
            .toString(), //提交的开始时间
          endTime: this.dayjs(
              new Date()
            )
            .format("YYYY-MM-DD")
            .toString(), //提交的结束时间
          page: 1,
          size: 10,

        },
        failureTypelist: [],
        tableData: [],
        multipleSelection: [],
        Launchdate: [
          this.dayjs(
            new Date()
          )
          .format("YYYY-MM-DD")
          .toString(),
          this.dayjs(
            new Date()
          )
          .format("YYYY-MM-DD")
          .toString(),
        ],
        deliveryfeelist: [],
      }
    },
    mounted() {
      this.getList();
      window.addEventListener("keydown", this.keyupEnter);
    },
    destroyed() {
      window.removeEventListener("keydown", this.keyDown, false);
    },
    methods: {
      // 选择框回车失焦
      selectBlur(e) {
        if (e.keyCode == 13) {
          this.$refs['failTypeRef'].blur();
          e.returnValue = false;
        }
      },
      keyupEnter() {
        if (window.event.keyCode == 13) {
          this.handleFilter(this.Launchdate); // 查询事件
        }
      },
      //如果页面有keep-alive缓存功能，这个函数会触发
      activated() {
        window.addEventListener("keydown", this.keyupEnter);
      },
      deactivated() {
        window.removeEventListener("keydown", this.keyupEnter);
      },
      getList() {
        getKingdeeSynchronizationFailPage(this.Synchronizeform).then(res => {
          this.tableData = res.data.data.rows;
          this.total = res.data.data.total;
        })
        //
      },
      handlefailureType() { //失败类型下拉
        kingdeefailtype('').then(res => {
          this.failureTypelist = res.data.data
        })
      },
      handleSynchronize() { //同步到金蝶，
        if (this.multipleSelection.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        } else {
          let xmbzNos = [];
          this.multipleSelection.map(item => {
            xmbzNos.push(item.id);
          });
          synchronizationKingdeeFailOrder({
            ids: xmbzNos
          }).then(res => {
            if (res.data.code == 200) {
              this.$notify({
                title: "同步数据",
                message: "同步金蝶成功",
                type: "success",
                duration: 2000
              });
              this.getList()
            }

          })

        }

      },
      handleFilter(times) { //查询
        if (times) {
          this.Synchronizeform.startTime = this.dayjs(
              times[0]
            )
            .format("YYYY-MM-DD")
            .toString();
          this.Synchronizeform.endTime = this.dayjs(
              times[1]
            )
            .format("YYYY-MM-DD")
            .toString();
        }
        var time1 = Date.parse(this.dayjs(
            times[0]
          )
          .format("YYYY-MM-DD 00:00:00")
          .toString());
        var time2 = Date.parse(this.dayjs(
            times[1]
          )
          .format("YYYY-MM-DD 00:00:00")
          .toString());
        //讲两个时间相减，求出相隔的天数
        var dayCount = Math.abs(time2 - time1) / 1000 / 60 / 60 / 24;
        if (dayCount >= 31) {
          this.$message({
            showClose: true,
            message: "时间间隔不可超过31天",
            type: "warning"
          });
        } else {
          this.Synchronizeform.page = 1;
          this.getList()
        }
      },
      handleSelectionChange(val) { //多选
        this.multipleSelection = val;

      },
      // handleExport(Synchronizeform, times) {
      //   if (times) {
      //     this.Synchronizeform.startTime = this.dayjs(
      //         times[0]
      //       )
      //       .format("YYYY-MM-DD")
      //       .toString();
      //     this.Synchronizeform.endTime = this.dayjs(
      //         times[1]
      //       )
      //       .format("YYYY-MM-DD")
      //       .toString();
      //   }
      //   var time1 = Date.parse(this.dayjs(
      //       times[0]
      //     )
      //     .format("YYYY-MM-DD 00:00:00")
      //     .toString());
      //   var time2 = Date.parse(this.dayjs(
      //       times[1]
      //     )
      //     .format("YYYY-MM-DD 00:00:00")
      //     .toString());
      //   //讲两个时间相减，求出相隔的天数
      //   var dayCount = Math.abs(time2 - time1) / 1000 / 60 / 60 / 24;
      //   if (dayCount >= 31) {
      //     this.$message({
      //       showClose: true,
      //       message: "时间间隔不可超过31天",
      //       type: "warning"
      //     });
      //   } else {
      //     // const {
      //     //   user
      //     // } = this.$store.state
      //     // var user = JSON.parse(localStorage.getItem('saber-userInfo'));
      //     // window.open(
      //     //   `/api/xmbz-statistics/orderStatistics/downLoadExcel?excelType=ABNORMAL&startTime=${this.Abnormalform.startTime}&endTime=${this.Abnormalform.endTime}&deptIds=${Abnormalform.deptIds}&blade-auth=bearer ${user['content'].accessToken}`
      //     // )
      //   }

      // },

    }
  }
</script>

<style lang='scss' scoped>
  .Synchronize {

    .filter_container {

      .el-form-item {
        margin-bottom: 22px !important;
      }

      .Synchronizeflex {
        /* display: flex; */
      }

      .Synchronizeflex2 {
        display: flex;
        justify-content: flex-end;
      }
    }
  }
</style>
